//
//  HBFindPwdSecondCtrl.m
//  HuoBao
//
//  Created by chaiyanan on 15/11/26.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBFindPwdSecondCtrl.h"
#import "HBLoginCtrl.h"
#import "CheckValid.h"
#import "HBResetUserPwdParam.h"
#import "HBResetUserPwdParser.h"
#import "NSString+MKNetworkKitAdditions.h"

#define topMargan  (IsIphone4?165:(IsIphone5?165:(IsIphone6?165:165)))
#define leftMargan  (IsIphone4?40:(IsIphone5?40:(IsIphone6?40:40)))

@interface HBFindPwdSecondCtrl ()
<UITextFieldDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) UITextField *pwdTX;
@property (nonatomic, strong) UILabel *msgLable;
@property (nonatomic, strong) UIButton *submitBtn;
@property (nonatomic, strong) UIButton *clearBtn;
@property (nonatomic, strong) UIButton *seeBtn;

@end

@implementation HBFindPwdSecondCtrl

#pragma mark -
#pragma mark - system

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)buildLayout
{
    [super buildLayout];
    self.title = @"设置新密码";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextFieldTextDidChangeNotification object:nil];
    
    self.scrollView = [self createScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) contentSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-64) andSuperView:self.view];
    self.bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    self.bgImageView.image = [UIImage imageNamed:@"login_pubbg"];
    self.bgImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickToEndEdit)];
    [self.bgImageView addGestureRecognizer:tapG];
    [self.scrollView addSubview:self.bgImageView];
    
    self.pwdTX = [self createTFWithPlaceHolder:@"请输入密码" placeHolderColor:[LCCommon getColor:@"585858"] font:[UIFont systemFontOfSize:15] color:[LCCommon getColor:@"ffffff"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, topMargan-18, SCREEN_WIDTH-2*(leftMargan), 50) superView:self.bgImageView];
    self.pwdTX.secureTextEntry = YES;
    
    UIView *seperatorLine1 = [self createSepratorLineWithFrame:CGRectMake(leftMargan, self.pwdTX.y+self.pwdTX.height, SCREEN_WIDTH-2*(leftMargan), 1/([UIScreen mainScreen].scale)) backgroundColor:[LCCommon getColor:@"a8a8a8"] superView:self.bgImageView];
    
    self.msgLable = [self createLableWithText:@"密码为6到12位的数字和字母组合" font:[UIFont systemFontOfSize:14.0f] color:[LCCommon getColor:@"fff25e"] textAlignment:NSTextAlignmentLeft frame:CGRectMake(leftMargan, seperatorLine1.y, SCREEN_WIDTH-2*(leftMargan), 45) superView:self.bgImageView];
    self.msgLable.hidden = NO;
    
    self.submitBtn = [self createButtonWithFrame:CGRectMake(leftMargan, seperatorLine1.y+45, SCREEN_WIDTH-2*(leftMargan), 45) normalBackgroundColor:[UIColor whiteColor] disabledBackgroundColor:[LCCommon getColor:@"a8a8a8"] higlightedBackgroundColor:[LCCommon getColor:Btn_Selected] normalFontColor:[LCCommon getColor:@"070707"] higlightedFontColor:[LCCommon getColor:@"070707"] disabledFontColor:[LCCommon getColor:@"070707"] title:@"确定" textAlignment:NSTextAlignmentCenter font:[UIFont systemFontOfSize:18] superView:self.bgImageView];
    
    UIImage *seeImage = [UIImage imageNamed:@"login_close"];
    self.seeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.seeBtn.frame = CGRectMake(SCREEN_WIDTH-seeImage.size.width-(leftMargan), self.pwdTX.y+(self.pwdTX.height-seeImage.size.height)/2, seeImage.size.width, seeImage.size.height);
    [self.seeBtn setImage:[UIImage imageNamed:@"login_close"] forState:UIControlStateNormal];
    [self.seeBtn setImage:[UIImage imageNamed:@"login_open"] forState:UIControlStateSelected];
    [self.seeBtn addTarget:self action:@selector(clickToSeePwd:) forControlEvents:UIControlEventTouchUpInside];
    [self.bgImageView addSubview:self.seeBtn];
    
    self.pwdTX.frame = CGRectMake(leftMargan, topMargan-18, SCREEN_WIDTH-2*(leftMargan)-10-seeImage.size.width, 50);
    
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -
#pragma mark - private

- (UIScrollView *)createScrollViewWithFrame:(CGRect)frame contentSize:(CGSize)contentSize andSuperView:(UIView *)superView
{
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:frame];
    scrollView.contentSize = contentSize;
    scrollView.bounces = NO;
    [superView addSubview:scrollView];
    return scrollView;
}

- (UITextField *)createTFWithPlaceHolder:(NSString *)placeHolder placeHolderColor:(UIColor *)placeColor font:(UIFont *)font color:(UIColor *)fontColor textAlignment:(NSTextAlignment)textAlignment frame:(CGRect)frame superView:(UIView *)superView
{
    UITextField *textField = [[UITextField alloc]initWithFrame:frame];
    textField.backgroundColor = [UIColor clearColor];
    textField.placeholder = placeHolder;
    textField.font = font;
    textField.textColor = fontColor;
    textField.textAlignment = textAlignment;
    textField.delegate = self;
    [textField setValue:placeColor forKeyPath:@"_placeholderLabel.textColor"];
    [superView addSubview:textField];
    return textField;
}

- (UILabel *)createLableWithText:(NSString *)text font:(UIFont *)font color:(UIColor *)fontColor textAlignment:(NSTextAlignment)textAlignment frame:(CGRect)frame superView:(UIView *)superView
{
    UILabel *lable = [[UILabel alloc]initWithFrame:frame];
    lable.backgroundColor = [UIColor clearColor];
    lable.text = text;
    lable.font = font;
    lable.textColor = fontColor;
    lable.textAlignment = textAlignment;
    [superView addSubview:lable];
    return lable;
}

- (UIView *)createSepratorLineWithFrame:(CGRect)frame backgroundColor:(UIColor *)bgColor superView:(UIView *)superView
{
    UIView *sepratorLine = [[UIView alloc]initWithFrame:frame];
    sepratorLine.backgroundColor = bgColor;
    [superView addSubview:sepratorLine];
    return sepratorLine;
}

- (UIButton *)createButtonWithFrame:(CGRect)frame normalBackgroundColor:(UIColor *)normalBGColor disabledBackgroundColor:(UIColor *)disabledBGColor higlightedBackgroundColor:(UIColor *)higlightedBGColor  normalFontColor:(UIColor *)normalFontColor higlightedFontColor:(UIColor *)higlightedFontColor disabledFontColor:(UIColor *)disabledFontColor title:(NSString *)title textAlignment:(NSTextAlignment)textAlignment font:(UIFont *)font superView:(UIView *)superView
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setBackgroundColor:normalBGColor];
    [button setBackgroundColor:normalBGColor forState:UIControlStateNormal];
    [button setBackgroundColor:disabledBGColor forState:UIControlStateDisabled];
    [button setBackgroundColor:higlightedBGColor forState:UIControlStateHighlighted];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:normalFontColor forState:UIControlStateNormal];
    [button setTitleColor:disabledFontColor forState:UIControlStateDisabled];
    [button setTitleColor:higlightedFontColor forState:UIControlStateHighlighted];
    button.titleLabel.font = font;
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [superView addSubview:button];
    button.enabled = NO;
    [button.layer setCornerRadius:4.0f];
    button.layer.masksToBounds = YES;
    return button;
}

- (void)showTFClearBtnWithTextField:(UITextField *)textField
{
//    LLog(@"textFiled.frame:%@",NSStringFromCGRect(textField.frame));
    UIImage *clearIamge = [UIImage imageNamed:@"login_clearn"];
    UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    clearBtn.frame = CGRectMake(textField.width+textField.x-clearIamge.size.width, textField.y+(textField.height-clearIamge.size.height)/2, clearIamge.size.width, clearIamge.size.height);
//    LLog(@"%@",NSStringFromCGRect(clearBtn.frame));
    [clearBtn setImage:clearIamge forState:UIControlStateNormal];
    [clearBtn addTarget:self action:@selector(clickToClearTF:) forControlEvents:UIControlEventTouchUpInside];
    [self.bgImageView addSubview:clearBtn];
    [self.bgImageView bringSubviewToFront:clearBtn];
    self.clearBtn = clearBtn;
}

- (void)hideTFClearBtn
{
    [self.clearBtn removeFromSuperview];
    self.clearBtn = nil;
    
}

#pragma mark -
#pragma mark - active

- (void)clickToSeePwd:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected)
    {
        self.pwdTX.secureTextEntry = NO;
    }
    else
    {
        self.pwdTX.secureTextEntry = YES;
    }
}

- (void)clickToClearTF:(UIButton *)sender
{
    self.pwdTX.text = @"";
    [self textDidChange];
    
}

- (void)clickToEndEdit
{
    [self.pwdTX resignFirstResponder];

}

- (void)clickButton:(UIButton *)sender
{
    if (sender == self.submitBtn)
    {
        if (![CheckValid isBothNumberAndCharString:self.pwdTX.text limitedLengthMoreThan:6 lessThan:12])
        {
            self.msgLable.hidden = NO;
            self.msgLable.text = @"密码为6到12位的数字和字母组合";
        }
        else
        {
            [self requestToSubmit];
        }
//        if ([CheckValid checkStrIsEmpty:self.pwdTX.text])
//        {
//            self.msgLable.hidden = NO;
//            self.msgLable.text = @"请输入密码";
//        }
//        else
//        {
//            [self requestToSubmit];
//        }
    }
}


#pragma mark -
#pragma mark - delegate


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *toBeString = textField.text;
    
    UITextInputMode *currentInputMode = textField.textInputMode;
    NSString *lang = [currentInputMode primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            
            if (toBeString.length >= 12) {
                
                self.pwdTX.text = [toBeString substringToIndex:12];
                if ([string isEqualToString:@""])
                {
                    return YES;
                }
                else
                {
                    return NO;
                }
                
            }
            
            
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length >= 12) {
            
            self.pwdTX.text = [toBeString substringToIndex:12];
            if ([string isEqualToString:@""])
            {
                return YES;
            }
            else
            {
                return NO;
            }
            
        }
    }

    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //    [self showTFClearBtnWithTextField:textField];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return YES;
}

#pragma mark -
#pragma mark - notify

-(void)textDidChange{
    
//    self.msgLable.text = @"";
    
//    if (self.pwdTX.text.length > 0)
//    {
//        self.submitBtn.enabled = YES;
//    }else{
//        
//        self.submitBtn.enabled = NO;
//    }
    
    if (self.pwdTX.text.length>=6)
    {
        if (![CheckValid isBothNumberAndCharString:self.pwdTX.text limitedLengthMoreThan:6 lessThan:12])
        {
            self.submitBtn.enabled = NO;
            self.msgLable.hidden = NO;
            self.msgLable.text = @"密码为6到12位的数字和字母组合";
        }
        else
        {
//            self.msgLable.text = @"";
            self.submitBtn.enabled = YES;
        }
    }
    else
    {
//        self.msgLable.text = @"";
        self.submitBtn.enabled = NO;
    }
}

- (void)keyboardDidHide:(NSNotification *)notification {
    if ([self.pwdTX isFirstResponder])
    {
        
    }
    else
    {
        [self hideTFClearBtn];
        
    }
}

- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView animateWithDuration:animationDuration animations:^{
        CGPoint contentOffset = _scrollView.contentOffset;
        contentOffset.y = 0;
        _scrollView.contentOffset = contentOffset;
    } completion:^(BOOL finished) {
        
    }];
    
    _scrollView.contentSize = _scrollView.bounds.size;
}

- (void)keyboardWillShow:(NSNotification *)notification {
    
    UITextField *text ;
    for (UITextField *field in _bgImageView.subviews) {
        if (field.isFirstResponder) {
            text = field;
            
        }
    }
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView animateWithDuration:animationDuration animations:^{
        if (CGRectGetMaxY(text.frame) - _scrollView.contentOffset.y < SCREEN_HEIGHT - 64 - (keyboardRect.size.height+30))
        {
            
        }
        else
        {
            CGPoint contentOffset = _scrollView.contentOffset;
            contentOffset.y += (CGRectGetMaxY(text.frame) - _scrollView.contentOffset.y)-(SCREEN_HEIGHT - 64 - (keyboardRect.size.height+30));
            _scrollView.contentOffset = contentOffset;
            
        }
        
    } completion:^(BOOL finished) {
        [self hideTFClearBtn];
        [self showTFClearBtnWithTextField:text];
    }];
    
    CGSize contentSize = _scrollView.contentSize;
    contentSize.height = _scrollView.bounds.size.height + keyboardRect.size.height;
    _scrollView.contentSize = contentSize;
}


#pragma mark -
#pragma mark - request

- (void)requestToSubmit
{
    self.msgLable.text = @"";
    [CustomLoadingView showHudToView:self.view];
    HBResetUserPwdParam *param = [[HBResetUserPwdParam alloc]init];
    param.mobile = self.mobile;
    param.password = self.pwdTX.text.md5;
    HBResetUserPwdParser *parser = [[HBResetUserPwdParser alloc]init];
    [NetCenter postDataFromURL:Method_resetUserPwd params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code==0)
        {
            for (UIViewController *vc in self.navigationController.viewControllers)
            {
                if ([vc isKindOfClass:[HBLoginCtrl class]])
                {
                    [self.navigationController popToViewController:vc animated:YES];
                }
            }
//            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else
        {
            self.msgLable.hidden = NO;
            self.msgLable.text = myResult.message;
        }
        [CustomLoadingView hideHudForView:self.view];
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        self.msgLable.text = [error description];
    }];
}


@end
